package com.wangzhen.codebase;

public class VolatileDemo {

    int x = 0;
    volatile boolean flag;

    public void write(){
        flag = true;
        x = 42;
    }

    public void read() {
        if (flag) {
            System.out.println(x);
        }else {
            System.out.println("---");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileDemo demo = new VolatileDemo();
        Thread t1 = new Thread(()-> {demo.write();});
        Thread t2 = new Thread(()-> {demo.read();});

        t1.start();t2.start();

        t1.join();
        t2.join();


    }
}
